// 使用 D8 内置的 readbuffer 函数读取 Wasm 文件
const buffer = readbuffer("/home/sjk/桌面/asc_test/build/test.wasm");

// 定义初始化和调用 WebAssembly 模块的函数
async function instantiateWasm(buffer) {
    const importObject = {
        env: {
            abort: function (message, fileName, lineNumber, columnNumber) {
                throw new Error(`${message} in ${fileName}:${lineNumber}:${columnNumber}`);
            }
        }
    };

    const module = await WebAssembly.compile(buffer);
    const instance = await WebAssembly.instantiate(module, importObject);

    const memory = instance.exports.memory;
    const dataview = new DataView(memory.buffer);

    // 将数组转为 WebAssembly 线性内存格式
    function lowerArray(values) {
        const length = values.length;
        const pointer = instance.exports.__pin(instance.exports.__new(length << 2, 1));
        for (let i = 0; i < length; i++) {
            dataview.setInt32(pointer + (i << 2), values[i], true);
        }
        instance.exports.__unpin(pointer);
        return pointer;
    }

    // 从 WebAssembly 线性内存中提取数组
    function liftArray(pointer, length) {
        const result = [];
        for (let i = 0; i < length; i++) {
            result.push(dataview.getInt32(pointer + (i << 2), true));
        }
        return result;
    }

    return {
        baselineTest: () => instance.exports.baselineTest(),
        noInputWithOutput: () => {
            const resultPointer = instance.exports.noInputWithOutput();
            return liftArray(resultPointer, 1000);
        },
        withInputAndOutput: (numbers) => {
            const inputPointer = lowerArray(numbers);
            const resultPointer = instance.exports.withInputAndOutput(inputPointer);
            return liftArray(resultPointer, 1000);
        },
        withInputNoOutput: (numbers) => {
            const inputPointer = lowerArray(numbers);
            instance.exports.withInputNoOutput(inputPointer);
        }
    };
}

// 测试代码
async function test() {
    const wasmFunctions = await instantiateWasm(buffer);

    const inputArray = new Array(1000).fill(0).map((_, i) => i + 1);//大于2000会“Offset is outside the bounds of the DataView”
    const iterations = 100;
    //wasmFunctions.baselineTest();//初始化
    // Baseline Test
    const startBaseline = Date.now();
    for (let i = 0; i < iterations; i++) {
        wasmFunctions.baselineTest();
    }
    const endBaseline = Date.now();
    
    print(`Baseline Test: ${endBaseline - startBaseline}ms`);

    // No Input, With Output
     //let noInputResult = wasmFunctions.noInputWithOutput();//用于初始化
    const startNoInput = Date.now();
   
    for (let i = 0; i < iterations; i++) {
        noInputResult = wasmFunctions.noInputWithOutput();
    }
    const endNoInput = Date.now();
    print(`No Input, With Output: ${endNoInput - startNoInput}ms, Result Length: ${noInputResult.length}`);

    // With Input, With Output

    const startWithInputOutput = Date.now();
    let withInputOutputResult;
    for (let i = 0; i < iterations; i++) {
        withInputOutputResult = wasmFunctions.withInputAndOutput(inputArray);
    }
    const endWithInputOutput = Date.now();
    print(`With Input, With Output: ${endWithInputOutput - startWithInputOutput}ms, Result Length: ${withInputOutputResult.length}`);

    // With Input, No Output
    // wasmFunctions.withInputNoOutput(inputArray);//用于初始化
    const startWithInputNoOutput = Date.now();
    for (let i = 0; i < iterations; i++) {
        wasmFunctions.withInputNoOutput(inputArray);
    }
    const endWithInputNoOutput = Date.now();
    print(`With Input, No Output: ${endWithInputNoOutput - startWithInputNoOutput}ms`);
}

// 运行测试
test().catch((err) => print(`Error: ${err}`));
